/************
 * 权限控制中使用的ajax封装
 * Created by donkey on 2017/12/21
 ************/
import axios from 'axios'
import store from '@/store'
import qs from 'qs'

const Message = window.Vue.prototype.$message;

// 创建axios实例
const service = axios.create({
    withCredentials:true,
    baseURL: BASE_URL,
    // timeout:10000,
    headers: {
        'Content-Type':'application/x-www-form-urlencoded'//默认以formdata形式发送数据
    },
})

function newservice() {
    window.sequence++;
    return service.apply(this, arguments);
}

for (let key in service) {
    newservice[key]  = service[key];
}
newservice.post = (url,entity,config) => {
    if (window.sequence == 0) {
        window._setLoading(true);
    }
    window.sequence++;
    if(config) {
        return service
            .post(url, entity,config)
            .catch(error => {
                console.log(error);
            });
    }
    return service
        .post(url, entity)
        .catch(error => {
            console.log(error);
        });
}
newservice.get = (url,entity) => {
    if (window.sequence == 0) {
        window._setLoading(true);
    }
    window.sequence++;
    return service
        .get(url, entity)
        .catch(error => {
            console.log(error);
        });
}


// request拦截器
newservice.interceptors.request.use(config => {
    const contentType = config.headers['Content-Type']

    if (config.data && contentType) {//处理post请求
        // 发送json类型
        if (contentType.indexOf('application/json')>=0 && typeof config.data==='object') {
            config.data = JSON.stringify(config.data)//转JSON字符串
        }

        // 发送form类型
        if(contentType.indexOf('application/x-www-form-urlencoded')>=0){
            config.data = qs.stringify(config.data)//用qs处理data
        }
    }
    return config
}, error => {
    // Do something with request error
    console.error(error) // for debug
    Promise.reject(error)
})
// respone拦截器
newservice.interceptors.response.use(
    response => {
        window.sequence--;
        setTimeout(() => {
            if(window.sequence == 0) {
                window._setLoading(false);
            }
        }, 50);
        const res = response.data;
        if(res.code === "403" || res.code === "401"){
            //session过期
            sessionStorage.setItem('login', null) //
            Message({
                showClose:true,
                message:res.message,
                type:'error',
                onClose:() => {
                    store.dispatch('FedLogout').then(() => {})
                },
                duration : 500
            });
            return Promise.reject(new Error('未登录'))
        } else if(res.code === "loginerror") {
            Message({
                showClose:true,
                message:res.message,
                type:'error'
            });
            return Promise.reject(new Error('未登录'))
        }
        return res;
    },
    error => {
        window.sequence--;
        setTimeout(() => {
            if(window.sequence == 0) {
                window._setLoading(false);
            }
        }, 100);
        if(error.response.status === 401) {
            sessionStorage.setItem('login', null) //
            Message({
                showClose:true,
                message:error.response.data.message,
                type:'error',
                onClose:() => {
                    store.dispatch('FedLogout').then(() => {})
                },
                duration : 1000
            });
        } else {
            console.error(error.message)
            /*Message({
                message:error.message,
                type:'error',
                // duration:3 * 1000,
                showClose:true
            })*/
        }
        return Promise.reject(error)
    }
)

//往全局添加一个原生axios
Object.defineProperty(window.Vue.prototype, '$axios', {
    value:axios
});

export default newservice
